package mya.mes.mdc.model.tag.convert;


import mya.mes.mdc.model.tag.MdcTag;
import mya.mes.mdc.model.tag.ViewTag;

import java.util.ArrayList;
import java.util.List;

public class ViewTagBuilder {

    public ViewTag build(String key, List<MdcTag> list) {
        ViewTag value = new ViewTag();

        value.tagName = list.get(0).viewTagName;
        value.shop = list.get(0).shop;
        value.area = list.get(0).area;
        value.section = list.get(0).section;

        value.fullTagName = key;//value.shop + "_"  + value.area  + "_"  + value.tagName;
        if (value.shop == null) {
            System.out.println("ViewTagBuilder value.shop == null");
        }
        if (value.area == null) {
            System.out.println("ViewTagBuilder value.area == null");
        }
        MdcTag[] digitsArray = new MdcTag[PlcTagType.digitsTagArray.length];
        MdcTag[] posteArray = new MdcTag[PlcTagType.posteTagArray.length];

        list.forEach(mdcTag -> {
            mdcTag.viewTag = value;
            if (mdcTag.alarmTag != null) {
                if (value.alarmTagList == null) {
                    value.alarmTagList = new ArrayList<>();
                }
                value.alarmTagList.add(mdcTag);
                return;
            }

            for (int i = 0; i < PlcTagType.digitsTagArray.length; i++) {
                if (PlcTagType.digitsTagArray[i].equals(mdcTag.plcTagType)) {
                    digitsArray[i] = mdcTag;
                    return;
                }
            }

            for (int i = 0; i < PlcTagType.posteTagArray.length; i++) {
                if (PlcTagType.posteTagArray[i].equals(mdcTag.plcTagType)) {
                    posteArray[i] = mdcTag;
                    return;
                }
            }

            if (value.mdcTagList == null) {
                value.mdcTagList = new ArrayList<>();
            }
            value.mdcTagList.add(mdcTag);
        });

        boolean hasDigits = false;
        boolean hasPoste = false;
        for (MdcTag mdcTag : digitsArray) {
            if (mdcTag != null) {
                hasDigits = true;
                break;
            }
        }
        for (MdcTag mdcTag : posteArray) {
            if (mdcTag != null) {
                hasPoste = true;
                break;
            }
        }

        if (hasDigits) {
            value.digitsTagArray = digitsArray;
        }

        if (hasPoste) {
            value.posteTagArray = posteArray;
        }
        return value;
    }
}


